from bs4 import BeautifulSoup
import json
import re
import requests
import time
import os
from urllib.parse import urljoin

def load_config():
    """加载配置文件"""
    config_file = "config.json"
    
    # 默认配置
    default_config = {
        "extract_revisions": {
            "input_html_file": "ebay_cosplay_results_latest.html",
            "output_html_file": "ebay_cosplay_results_with_quantity_tooltip.html",
            "quantity_data_file": "quantity_data.json"
        }
    }
    
    try:
        if os.path.exists(config_file):
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
            
            # 合并配置，确保extract_revisions部分存在
            if "extract_revisions" not in config:
                config["extract_revisions"] = default_config["extract_revisions"]
            else:
                # 确保所有必需的键都存在
                for key in default_config["extract_revisions"]:
                    if key not in config["extract_revisions"]:
                        config["extract_revisions"][key] = default_config["extract_revisions"][key]
            
            print("配置文件加载成功")
            return config
        else:
            print("配置文件不存在，使用默认配置")
            return default_config
    except Exception as e:
        print(f"加载配置文件失败: {e}，使用默认配置")
        return default_config

def extract_quantity_info_from_url(url):
    """从URL中提取包含Quantity的原始行数据，保持数据原始性"""
    quantity_data = []
    
    try:
        # 添加延迟避免请求过快
        time.sleep(1.0)  # 增加延迟时间
        
        # 发送HTTP请求获取页面内容
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'none',
            'Cache-Control': 'max-age=0'
        }
        
        response = requests.get(url, headers=headers, timeout=60)  # 增加超时时间
        response.raise_for_status()
        
        # 解析HTML内容
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # 查找修订历史表格
        revision_tables = soup.find_all('table')
        
        for table in revision_tables:
            # 查找表格中的修订记录
            rows = table.find_all('tr')
            
            for row in rows:
                # 获取行的所有单元格文本
                cells = row.find_all(['td', 'th'])
                row_text = ' '.join([cell.get_text(strip=True) for cell in cells])
                
                # 检查是否包含Quantity信息，如果包含就记录整行数据
                if 'Quantity' in row_text:
                    # 提取日期时间信息
                    date_time_match = re.search(r'(\w+ \d{1,2}, \d{4} \d{1,2}:\d{2}:\d{2} [AP]M [A-Z]{2,4})', row_text)
                    date_time = date_time_match.group(1) if date_time_match else "未知时间"
                    
                    # 创建结构化的Quantity记录，保持原始性
                    quantity_record = {
                        'date_time': date_time,
                        'quantity_type': 'Quantity',  # 统一类型，不拆分
                        'full_text': row_text
                    }
                    quantity_data.append(quantity_record)
        
        # 如果没有找到表格数据，尝试从文本中提取
        if not quantity_data:
            all_text = soup.get_text()
            lines = all_text.split('\n')
            
            current_date_time = "未知时间"
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                    
                # 检查是否是日期时间行
                date_time_match = re.search(r'(\w+ \d{1,2}, \d{4} \d{1,2}:\d{2}:\d{2} [AP]M [A-Z]{2,4})', line)
                if date_time_match:
                    current_date_time = date_time_match.group(1)
                
                # 检查是否包含Quantity信息，如果包含就记录整行数据
                if 'Quantity' in line:
                    quantity_record = {
                        'date_time': current_date_time,
                        'quantity_type': 'Quantity',  # 统一类型，不拆分
                        'full_text': line
                    }
                    quantity_data.append(quantity_record)
        
        print(f"从 {url} 提取到 {len(quantity_data)} 条原始Quantity数据")
        
    except requests.RequestException as e:
        print(f"请求 {url} 失败: {e}")
        quantity_data = [{'date_time': '错误', 'quantity_type': 'Quantity', 'full_text': f'请求失败: {str(e)}'}]
    except Exception as e:
        print(f"解析 {url} 数据失败: {e}")
        quantity_data = [{'date_time': '错误', 'quantity_type': 'Quantity', 'full_text': f'解析错误: {str(e)}'}]
    
    return quantity_data

def process_html_file(input_file, output_file):
    """处理HTML文件，添加气泡弹窗功能"""
    
    # 读取HTML文件
    with open(input_file, 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 查找所有View all revisions按钮
    revision_buttons = soup.find_all('button', class_='revision-btn')
    
    print(f"找到 {len(revision_buttons)} 个View all revisions按钮")
    
    quantity_data = {}
    
    for i, button in enumerate(revision_buttons):
        url = button.get('data-url')
        if url:
            print(f"处理第 {i+1} 个按钮: {url}")
            
            # 从实际URL中提取Quantity数据
            quantity_info = extract_quantity_info_from_url(url)
            
            # 将Quantity信息存储为JSON格式
            quantity_data[url] = quantity_info
            
            # 为按钮添加data-quantity属性
            button['data-quantity'] = json.dumps(quantity_info)
            
            # 添加title属性显示简要信息
            button['title'] = "查看库存更新记录"
            
            print(f"提取到Quantity信息: {len(quantity_info)}条")
    
    # 添加气泡弹窗的CSS样式
    style_tag = soup.new_tag('style')
    style_tag.string = """
    /* 气泡弹窗样式 */
    .tooltip {
        position: relative;
        display: inline-block;
    }
    
    .tooltip .tooltiptext {
        visibility: hidden;
        width: 600px;
        background-color: #333;
        color: #fff;
        text-align: left;
        border-radius: 6px;
        padding: 15px;
        position: absolute;
        z-index: 1001;
        bottom: 125%;
        left: 50%;
        margin-left: -300px;
        opacity: 0;
        transition: opacity 0.3s;
        font-size: 12px;
        line-height: 1.4;
        max-height: 400px;
        overflow-y: auto;
        box-shadow: 0 4px 8px rgba(0,0,0,0.3);
    }
    
    .tooltip .tooltiptext::after {
        content: "";
        position: absolute;
        top: 100%;
        left: 50%;
        margin-left: -5px;
        border-width: 5px;
        border-style: solid;
        border-color: #333 transparent transparent transparent;
    }
    
    .tooltip:hover .tooltiptext {
        visibility: visible;
        opacity: 1;
    }
    
    /* 表格样式 */
    .quantity-table {
        width: 100%;
        border-collapse: collapse;
        font-family: monospace;
        font-size: 11px;
    }
    
    .quantity-table th {
        background-color: #444;
        color: #fff;
        padding: 8px;
        text-align: left;
        border: 1px solid #555;
        font-weight: bold;
    }
    
    .quantity-table td {
        padding: 6px 8px;
        border: 1px solid #555;
        background-color: #222;
    }
    
    .quantity-table tr:hover td {
        background-color: #444;
    }
    
    .quantity-item {
        margin: 2px 0;
        padding: 2px;
        font-family: monospace;
    }
    
    /* 确保按钮样式不变 */
    .revision-btn {
        background-color: #007bff;
        color: white;
        border: none;
        padding: 5px 10px;
        border-radius: 3px;
        cursor: pointer;
        font-size: 12px;
        transition: background-color 0.3s;
    }
    
    .revision-btn:hover {
        background-color: #0056b3;
    }
    
    .revision-btn:active {
        background-color: #004085;
    }
    """
    
    # 将样式添加到head中
    if soup.head:
        soup.head.append(style_tag)
    
    # 为每个按钮添加tooltip包装
    for button in revision_buttons:
        # 创建tooltip包装器
        tooltip_div = soup.new_tag('div', **{'class': 'tooltip'})
        
        # 获取按钮的父元素
        parent = button.parent
        
        # 将按钮移动到tooltip div中
        button.extract()
        tooltip_div.append(button)
        
        # 创建tooltip文本内容
        tooltip_text = soup.new_tag('div', **{'class': 'tooltiptext'})
        
        # 获取Quantity信息
        quantity_json = button.get('data-quantity', '[]')
        try:
            quantity_info = json.loads(quantity_json)
        except:
            quantity_info = []
        
        if quantity_info:
            # 创建表格
            table = soup.new_tag('table', **{'class': 'quantity-table'})
            
            # 创建表头
            thead = soup.new_tag('thead')
            header_row = soup.new_tag('tr')
            
            # 添加表头列（只显示日期时间和完整记录）
            headers = ['日期时间', '完整记录']
            for header_text in headers:
                header_cell = soup.new_tag('th')
                header_cell.string = header_text
                header_row.append(header_cell)
            
            thead.append(header_row)
            table.append(thead)
            
            # 创建表格主体
            tbody = soup.new_tag('tbody')
            
            for qty_record in quantity_info:
                row = soup.new_tag('tr')
                
                # 日期时间列
                date_cell = soup.new_tag('td')
                date_cell.string = qty_record.get('date_time', '未知时间')
                row.append(date_cell)
                
                # 完整记录列（保持原始性）
                detail_cell = soup.new_tag('td')
                detail_cell.string = qty_record.get('full_text', '')
                row.append(detail_cell)
                
                tbody.append(row)
            
            table.append(tbody)
            tooltip_text.append(table)
        else:
            tooltip_text.string = "暂无Quantity信息"
        
        tooltip_div.append(tooltip_text)
        
        # 将tooltip div添加到原来的位置
        parent.append(tooltip_div)
    
    # 保存修改后的HTML
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(str(soup))
    
    print(f"处理完成！输出文件: {output_file}")
    print(f"成功处理了 {len(quantity_data)} 个商品的Quantity信息")
    
    return quantity_data

if __name__ == "__main__":
    # 加载配置
    config = load_config()
    
    # 从配置中获取文件名
    input_file = config["extract_revisions"]["input_html_file"]
    output_file = config["extract_revisions"]["output_html_file"]
    quantity_data_file = config["extract_revisions"]["quantity_data_file"]
    
    print(f"输入文件: {input_file}")
    print(f"输出文件: {output_file}")
    print(f"Quantity数据文件: {quantity_data_file}")
    
    # 检查输入文件是否存在
    if not os.path.exists(input_file):
        print(f"错误: 输入文件 {input_file} 不存在")
        print("请检查config.json中的input_html_file配置")
        exit(1)
    
    print("开始处理HTML文件...")
    quantity_data = process_html_file(input_file, output_file)
    
    # 保存Quantity数据到JSON文件
    with open(quantity_data_file, 'w', encoding='utf-8') as f:
        json.dump(quantity_data, f, ensure_ascii=False, indent=2)
    
    print(f"Quantity数据已保存到 {quantity_data_file}")